package com.jbwz.web.cms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jbwz.web.cms.entity.GoodsCr;
import com.jbwz.web.cms.entity.vo.GoodsCrVO;
import com.jbwz.web.cms.mapper.GoodsCrMapper;
import com.jbwz.web.cms.service.GoodsCrService;
import com.jbwz.web.common.base.BaseServiceImpl;
import com.jbwz.web.common.base.IBasePage;
import com.jbwz.web.common.util.BeanUtilCommon;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * 服务实现类
 *
 * @author yyh
 * @since 2022-02-03 09:32:08
 */
@Service
public class GoodsCrServiceImpl extends BaseServiceImpl<GoodsCrMapper, GoodsCr>
    implements GoodsCrService {

  @Override
  public IBasePage pageList(IBasePage page, GoodsCrVO vo) {
    //        return baseMapper.pageList(page, vo);
    return null;
  }

  @Override
  public void save(GoodsCrVO vo) {
    QueryWrapper<GoodsCr> querw =
        Wrappers.<GoodsCr>query()
            .eq("category_id", vo.getCategoryId())
            .eq("goods_id", vo.getGoodsId());
    List<GoodsCr> goodsCrs = baseMapper.selectList(querw);
    if (CollectionUtils.isEmpty(goodsCrs)) {
      save(toEntity(vo));
    }
  }

  @Transactional(rollbackFor = Exception.class)
  @Override
  public void updateSorted(GoodsCrVO vo) {
    List<GoodsCr> goodsCrs =
        vo.getSortList().stream()
            .map(
                v -> {
                  GoodsCr goodsCr = new GoodsCr();
                  goodsCr.setId(v.getId());
                  goodsCr.setSorted(v.getSorted());
                  return goodsCr;
                })
            .toList();
    updateBatchById(goodsCrs);
  }

  /**
   * 根据类别id查询
   *
   * @param id
   * @return
   */
  @Override
  public List<GoodsCr> findByCategoryId(Long id) {
    QueryWrapper<GoodsCr> query = Wrappers.<GoodsCr>query().eq("category_id", id);
    return baseMapper.selectList(query);
  }

  /**
   * 根据goodsId categoryId删除
   *
   * @param vo
   */
  @Override
  public void deleteByVO(GoodsCrVO vo) {
    if (Objects.isNull(vo.getCategoryId()) && Objects.isNull(vo.getGoodsId())) {
      return;
    }
    QueryWrapper<GoodsCr> querw =
        Wrappers.<GoodsCr>query()
            .eq("category_id", vo.getCategoryId())
            .eq("goods_id", vo.getGoodsId());
    baseMapper.delete(querw);
  }

  @Override
  public GoodsCrVO toVO(GoodsCr e) {
    GoodsCrVO vo = BeanUtilCommon.copy(e, new GoodsCrVO());
    return vo;
  }

  public GoodsCr toEntity(GoodsCrVO vo) {
    GoodsCr e = BeanUtilCommon.copy(vo, new GoodsCr());
    return e;
  }
}
